//
//  FilmDetailViewController.m
//  iCinema
//
//  Created by Maarten Tutak on 19/11/12.
//  Copyright (c) 2012 Robin Daniels. All rights reserved.
//

#import "FilmDetailViewController.h"
#import "VariableStore.h"
#import "JSONKit.h"

@interface FilmDetailViewController ()

@end

@implementation FilmDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    // Achtergrond instellen
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bg.jpg"]];
    self.view.backgroundColor = background;
    
    // FIX
    //   -> Controle moet gebeuren omdat anders de NavigationTitle een bug vertoont
    // Nagaan of de calling view 'Aanbiedingen' is
    if (self.navigationController.title == @"Aanbiedingen") {
        [[VariableStore sharedInstance] setCame_from_AanbiedingView:YES];
    }
    
    [[VariableStore sharedInstance] setDetail_back_buttonPressed:YES];
    // END FIX
    
    // Als de film gekocht is dient de knop als 'Play', anders als 'Aankopen'
    if (_isPlayable) {
        [_btnPlay setTitle:@"Play" forState:UIControlStateNormal];
    } else {
        [_btnPlay setTitle:@"Aankopen" forState:UIControlStateNormal];
    }
    
    // Informatie op het scherm zetten
    _titelLabel.text = _film.Titel;
    _AfbeeldingView.image = [[UIImage alloc] initWithData:_film.AfbeeldingData];
    _genreLabel.text = _film.Genre1;
    _studioLabel.text = [NSString stringWithFormat:@"%@, %@", _film.Studio, _film.Jaar];
    _duurLabel.text = [NSString stringWithFormat:@"Speeltijd van %@ minuten", _film.Looptijd];
    
    // Als er korting is -> berekenen hoeveel
    if (_film.KortingPercentage) {
        Float32 prijs = [_film.Prijs floatValue];
        Float32 korting = [_film.KortingPercentage floatValue];
        
        Float32 nieuwePrijs = prijs * (1 - korting);
        
        _prijsLabel.text = [NSString stringWithFormat:@"Nu kopen voor € %.2f", nieuwePrijs];
    } else {
        _prijsLabel.text = [NSString stringWithFormat:@"Nu kopen voor € %@", _film.Prijs];
    }

    _korteInhoudTextView.text = _film.KorteInhoud;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)PlayMovie:(id)sender {
    
    // Als de film gekocht is wordt een film afgespeeld
    if (_isPlayable) {

        NSMutableString *stream = [[NSMutableString alloc] initWithFormat:@"http://%@", [[VariableStore sharedInstance] global_ip]];
        [stream appendString:_film.Stream_url];
        [self playMovieAtURL:[[NSURL alloc] initWithString:stream]];
    
    // Als de film NIET gekocht is dan wordt de bestelling afgerond
    } else {
        
        NSString* aankoopURL = [NSString stringWithFormat:@"http://%@:8080/MyCinemaWebservice/webresources/REST/aankoop", [[VariableStore sharedInstance] global_ip]];
        
        // Dictionary maken met het Film_ID en Gebruiker_ID om te versturen naar de webservice
        NSMutableDictionary *nameElements = [NSMutableDictionary dictionary];
        [nameElements setObject:_film.Film_ID forKey:@"Film_ID"];
        [nameElements setObject:[[VariableStore sharedInstance] global_gebruiker].Gebruiker_ID forKey:@"Gebruiker_ID"];
        
        // Dictionary omzetten naar JSON; nodige variabele opvullen (jsonData, URL, request&error variable,...)
        NSString *JSON = [nameElements JSONString];
        NSData *theData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString: aankoopURL];
        NSString *postLength = [NSString stringWithFormat:@"%d", [theData length]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        NSError *error = NULL;
        NSHTTPURLResponse *response = nil;
        
        // De request zelf
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:theData];
        [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:&response error:&error];
        
        // Response code -> controle nummer
        NSInteger code = [response statusCode];
        
        // 200 = OK
        if (code == 200) {
            
            UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Aankoop gelukt!"
                                                              message:@"U kan de film afspelen op de account pagina."
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                                    otherButtonTitles:nil];
            [message show];
            
            [[VariableStore sharedInstance] setBought_movie:YES];
        
        // 409 = Conflict -> Betekent dat de gebruiker-film combinatie al in de database zit, maw de gebruiker heeft de film al gekocht
        } else if (code == 409){
            
            UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Aankoop niet nodig!"
                                                              message:@"U heeft deze film al gekocht."
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                                    otherButtonTitles:nil];
            [message show];
            
        // Andere fouten netjes melden
        } else {
            
            UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Oeps"
                                                              message:@"Er ging iets mis."
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                                    otherButtonTitles:nil];
            [message show];
            
        }
    }
}

- (void) playMovieAtURL: (NSURL*) theURL {
    
    // MoviePlayer klaarmaken
    _moviePlayer =  [[MPMoviePlayerController alloc] initWithContentURL:theURL];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:_moviePlayer];
    _moviePlayer.controlStyle = MPMovieControlStyleDefault;
    _moviePlayer.shouldAutoplay = YES;
    
    // Film afspelen
    [self.view addSubview:_moviePlayer.view];
    [_moviePlayer setFullscreen:YES animated:YES];

}

- (void) moviePlayBackDidFinish:(NSNotification*)notification {
    
    // Afhandelen
    MPMoviePlayerController *player = [notification object];
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:player];
    
    // Speler afsluiten
    if ([player respondsToSelector:@selector(setFullscreen:animated:)])
    {
        [player.view removeFromSuperview];
    }
}

- (void)viewDidUnload {
    [self setTitelLabel:nil];
    [self setAfbeeldingView:nil];
    [self setPlayButton:nil];
    [self setGenreLabel:nil];
    [self setStudioLabel:nil];
    [self setPrijsLabel:nil];
    [self setDuurLabel:nil];
    [self setKorteInhoudTextView:nil];
    [self setBtnPlay:nil];
    [self setKorteInhoudTextView:nil];
    [super viewDidUnload];
}

@end
